<template>
  <el-dialog :model-value="showSetExamRuleDialog" title="编辑题目规则" width="650" @close="resetForm"
    :close-on-click-modal="false">
    <el-alert :title="`规则：一共${editInfo.totalQuestions}道题目，每题${form.trueFalseScores}分，90分及格，考试时间${examTime}分钟`"
      type="primary" :closable="false" style="margin-bottom: 30px" />

    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="判断题：" prop="trueFalseCount">
        <el-row class="rule-item">
          <el-col :span="10">
            <div class="row-content">
              抽选<el-input type="number" v-model.number="form.trueFalseCount"
                style="width: 80px; margin: 0 3px"></el-input>道试题
            </div>
          </el-col>
          <el-col :span="10">
            <div class="row-content">
              每题<el-input type="number" v-model="form.trueFalseScores" style="width: 80px; margin: 0 3px"
                :disabled="true"></el-input>分
            </div>
          </el-col>
          <el-col :span="4">
            总共<span style="color: red">{{ form.trueFalseCount * form.trueFalseScores }}</span>分
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="单选题：" prop="singleChoiceCount">
        <el-row class="rule-item">
          <el-col :span="10">
            <div class="row-content">
              抽选<el-input type="number" v-model.number="form.singleChoiceCount" :disabled="isOnlySingleAndTrueFalse"
                style="width: 80px; margin: 0 3px"></el-input>道试题
            </div>
          </el-col>
          <el-col :span="10">
            <div class="row-content">
              每题<el-input type="number" v-model="form.singleChoiceScores" :disabled="true"
                style="width: 80px; margin: 0 3px"></el-input>分
            </div>
          </el-col>
          <el-col :span="4">
            总共<span style="color: red">{{
              form.singleChoiceCount * form.singleChoiceScores
            }}</span>分
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="多选题：" prop="multipleChoiceCount" v-if="!isOnlySingleAndTrueFalse">
        <el-row class="rule-item">
          <el-col :span="10">
            <div class="row-content">
              抽选<el-input type="number" v-model.number="form.multipleChoiceCount" :disabled="!isOnlySingleAndTrueFalse"
                style="width: 80px; margin: 0 3px"></el-input>道试题
            </div>
          </el-col>
          <el-col :span="10">
            <div class="row-content">
              每题<el-input type="number" v-model="form.multipleChoiceScores" :disabled="true"
                style="width: 80px; margin: 0 3px"></el-input>分
            </div>
          </el-col>
          <el-col :span="4">
            总共<span style="color: red">{{
              form.multipleChoiceCount * form.multipleChoiceScores
            }}</span>分</el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { setExamConfig } from '@/api/questionbank'

const props = defineProps({
  showSetExamRuleDialog: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return { id: '' }
    }
  }
})

const ruleFormRef = ref<FormInstance>()

interface Form {
  id: string
  trueFalseCount: number
  trueFalseScores: number
  singleChoiceCount: number
  singleChoiceScores: number
  multipleChoiceCount: number
  multipleChoiceScores: number
}

const form = reactive({
  id: '',
  trueFalseCount: 0,
  trueFalseScores: 0,
  singleChoiceCount: 0,
  singleChoiceScores: 0,
  multipleChoiceCount: 0,
  multipleChoiceScores: 0
})

const rules = reactive<FormRules<Form>>({
  trueFalseCount: [{ required: true, message: '不能为空', trigger: 'change' }],
  singleChoiceCount: [{ required: true, message: '不能为空', trigger: 'change' }],
  multipleChoiceCount: [{ required: true, message: '不能为空', trigger: 'change' }]
})

const examTime = computed(() => {
  return props.editInfo.categoryId === '5' ? '30' : '45'
})

const isOnlySingleAndTrueFalse = computed(() => {
  return !(
    props.editInfo.categoryId === '4' ||
    (props.editInfo.categoryId === '6' && ['2', '3'].includes(props.editInfo.carId))
  )
})

watch(
  () => [form.trueFalseCount, form.singleChoiceCount],
  ([trueFalse, singleChoice]) => {
    const total = Number(props.editInfo.totalQuestions) || 0

    if (isOnlySingleAndTrueFalse.value) {
      form.singleChoiceCount = Math.max(0, total - (Number(trueFalse) || 0))
    } else {
      form.multipleChoiceCount = Math.max(
        0,
        total - (Number(trueFalse) || 0) - (Number(singleChoice) || 0)
      )
    }
  },
  { immediate: true }
)

const editLoading = ref(false)

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (
        form.trueFalseCount + form.singleChoiceCount + form.multipleChoiceCount !==
        props.editInfo.totalQuestions
      ) {
        ElMessage.error('总题数不对')
        return
      }

      handleEdit()
    } else {
    }
  })
}

async function handleEdit() {
  try {
    editLoading.value = true
    const res = await setExamConfig(props.editInfo.id, {
      id: form.id,
      trueFalseCount: form.trueFalseCount,
      singleChoiceCount: form.singleChoiceCount,
      multipleChoiceCount: form.multipleChoiceCount
    })
    if (res.code === '00000') {
      emit('closeDialog', true)
      ElMessage.success('编辑成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

const emit = defineEmits(['closeDialog'])

const resetForm = () => {
  emit('closeDialog')
}

onMounted(() => {
  if (props.editInfo.id) {
    if (props.editInfo.totalQuestions === 100) {
      form.trueFalseScores = 1
      form.singleChoiceScores = 1
      form.multipleChoiceScores = 1
    } else if (props.editInfo.totalQuestions === 50) {
      form.trueFalseScores = 2
      form.singleChoiceScores = 2
      form.multipleChoiceScores = 2
    }

    form.id = props.editInfo.id
    form.singleChoiceCount = props.editInfo.singleChoiceCount
    form.trueFalseCount = props.editInfo.trueFalseCount
    form.multipleChoiceCount = props.editInfo.multipleChoiceCount
  }
})
</script>

<style scoped lang="scss">
.rule-item {
  width: 100%;
  padding-left: 20px;
}

.row-content {
  display: flex;
  align-items: center;
}
</style>
